package com.glsc.ngateway.opmanage.service.report.excel.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.glsc.ngateway.common.base.domain.mysql.opmanage.report.excel.PnLTrdLvRepo;
import com.glsc.ngateway.common.base.repo.mysql.opmanage.report.excel.PnLTrdLvRepoRepo;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

public class PnLTrdLvRepoListener extends AnalysisEventListener<PnLTrdLvRepo> {

    private static final int BATCH_COUNT = 3000;
    List<PnLTrdLvRepo> list=new ArrayList<PnLTrdLvRepo>();

    private PnLTrdLvRepoRepo pnLTrdLvRepoRepo;
    private String name;
    private Date date;

    public PnLTrdLvRepoListener(){
    }

    public PnLTrdLvRepoListener(PnLTrdLvRepoRepo pnLTrdLvRepoRepo, String name, Date date){
        this.pnLTrdLvRepoRepo=pnLTrdLvRepoRepo;
        this.name=name;
        this.date=date;
    }

    @Override
    public void invoke(PnLTrdLvRepo data, AnalysisContext analysisContext) {
//        analysisContext.readWorkbookHolder().setIgnoreEmptyRow(false);
        if(data.getTicket()!=null){
            data.setFundName(name);
            data.setDate(date);
            list.add(data);
        }
        // 达到BATCH_COUNT了，需要去存储一次数据库，防止数据几万条数据在内存，容易OOM
        if (list.size() >= BATCH_COUNT) {
            saveData();
            // 存储完成清理 list
            list.clear();
        }

    }
//    @Override
//    public boolean hasNext(AnalysisContext analysisContext){
//        if(RowTypeEnum.EMPTY.equals(analysisContext.readRowHolder().getRowType())){
//            doAfterAllAnalysed(analysisContext);
//            return false;
//        }
//        return super.hasNext(analysisContext);
//    }

    //读取表头内容
    @Override
    public void invokeHeadMap(Map<Integer, String> headMap, AnalysisContext context) {
    }
    //读取完成之后
    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        saveData();
    }

    private void saveData(){
        pnLTrdLvRepoRepo.saveAll(list);
    }
}